<?php

class Validation
{
	/**
	 * 过滤数据
	 * @param string $string
	 */
	public static function filterData( $string , $type = 2 )
	{
		$string = stripslashes( $string );
	    if ( $type == 0 )
	    {
	        $string = htmlspecialchars( $string );
	    }
	    elseif ( $type == 1 )
	    {
	        $string = htmlspecialchars( $string );
			$string = str_replace( "　" , ' ' , $string );
			$string = preg_replace( "/[\r\n\t ]{1,}/" , ' ' , $string );
	    }
	    elseif ( $type == 2 )
	    {
	        $string = htmlspecialchars( $string );
			$string = str_replace( "　" , '' , $string );
			$string = preg_replace( "/[\r\n\t ]/" , '' , $string );
	    }
	    elseif ( $type == 3 )
	    {
	        $string = preg_replace( "/[\r\n\t ]{1,}/" , ' ' , $string );
			$string = preg_replace( '/script/i' , 'ｓｃｒｉｐｔ' , $string );
			$string = preg_replace( "/<[\/]{0,1}(link|meta|ifr|fra)[^>]*>/i" , '' , $string );
	    }
	    return addslashes( $string );
	}
	
	/**
	 * 将html转换为文本
	 * @param string $str
	 */
	public static function html2text( $str )
	{
		$str = preg_replace( "/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU" , "" , $str );
		$alltext = "";
		$start = 1;
		for( $i = 0 ; $i < strlen( $str ) ; $i++ )
		{
			if( $start == 0 && $str[$i] == ">" )
			{
				$start = 1;
			}
			elseif( $start == 1 )
			{
				if( $str[$i] == "<" )
				{
					$start = 0;
					$alltext .= " ";
				}
				elseif( ord( $str[$i] ) > 31 )
				{
					$alltext .= $str[$i];
				}
			}
		}
		$alltext = str_replace( "　" , " " , $alltext );
		$alltext = preg_replace( "/&([^;&]*)(;|&)/" , "" , $alltext );
		$alltext = preg_replace( "/[ ]+/s" , " " , $alltext );
		return $alltext;
	}
}